package com.imooc.girl.aspect;

import com.imooc.girl.utils.AspectUtils;
import javassist.NotFoundException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @description:
 * @program: girl
 * @author: Administrator
 * @date: 2019/2/19 09:22
 */
@Aspect
@Component
public class HttpAspect {

    private static final Logger log = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.imooc.girl.controller.*.*(..))")
    public void matchLog() {

    }

    /**
     * 打印方法调用信息
     * @param joinPoint
     */
    @Before("matchLog()")
    public void logBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Signature signature = joinPoint.getSignature();
        // URL
        log.info("url={}", request.getRequestURL());
        // request method
        log.info("method={}", request.getMethod());
        // ip
        log.info("ip={}", AspectUtils.getRemoteAddr(request));
        // 类方法
        log.info("class_method={}.{}", signature.getDeclaringType(), signature.getName());
        // 参数
        String[] fieldsName = new String[0];
        try {
            fieldsName = AspectUtils.getFieldsName(this.getClass(), joinPoint.getTarget().getClass().getName(), signature.getName());
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        String argsStr = AspectUtils.getArgsString(joinPoint.getArgs(), fieldsName);
        log.info("args={}", argsStr);
    }

    @After("matchLog()")
    public void logAfter() {
        System.out.println("after");
    }

    @AfterReturning(value = "matchLog()", returning = "object")
    public void logAfterReturn(Object object) {
        log.info("response={}", object);
    }

}
